from rest_framework import serializers
from apps.system.models import User, Role


class UserSerializer(serializers.ModelSerializer):

    roles = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = '__all__'
        # fields = ["id", "username", "role", "create_time",  "update_time", "email"]
        extra_kwargs = {'password': {'write_only': True}}

    def get_roles(self, obj):
        """
            自定义序列化器字段的GET方法获取用户角色
            :param obj:
            :return:
        """
        user_id = obj.id
        roles = [i for i in Role.objects.filter(users=user_id, is_active=True).values('id', 'name')]
        # roles = ",".join(roles)
        return roles


